package com.keelau.ui.fx;

import com.keelau.idao.model.AliProduct;
import com.keelau.idao.model.AliProductExample;
import com.keelau.ui.view.AliCatalogTree;
import com.keelau.ui.view.AliProductView;
import com.keelau.repository.DataManager;
import com.keelau.ui.view.AliCataLogTreeItem;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class AliProductTableUI extends AnchorPane{

    //BorderPane borderPane;

    DataManager dataManager;

    SplitPane splitPane;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    ObservableList<AliProductView> data;

    ListProperty<AliProductView> lists = new SimpleListProperty<AliProductView>();

    LongProperty catalogProperty = new SimpleLongProperty(-1);

    StringProperty catalogNameProperty = new SimpleStringProperty("");

    //region -----搜索条件控件
    TextField proNameTxt ;
    CheckBox isShiliChk;
    CheckBox isFactoryChk;
    //endregion

    TreeTableView treeTableView;

    public TableView<AliProductView> tableView;

    public AliProductTableUI(){
        dataManager = UIDemo.context.getBean(DataManager.class);

        BorderPane borderPane = new BorderPane();
        //create toolbar
        createToolBar(borderPane);

        splitPane = new SplitPane();
        splitPane.setDividerPositions(0.2);
        //左边分类树
         treeTableView = buildAliCatalogTreeTableView();

        splitPane.getItems().add(treeTableView);

       // LoggerFactory.getLogger(this.getClass()).info("init table ui");
        //右边数据表
        tableView = buildProductTableView();
        tableView.setItems(data);
        initTableViewData();
        splitPane.getItems().add(tableView);
        //添加splitPane
        borderPane.setCenter(splitPane);


        getChildren().add(borderPane);
        setBottomAnchor(borderPane,0.0);
        setTopAnchor(borderPane,0.0);
        setLeftAnchor(borderPane,0.0);
        setRightAnchor(borderPane,0.0);
    }

    public ObservableList<AliProductView> initTableViewData() {
        AliProductExample aliProductExample = new AliProductExample();
        if(isFactoryChk!=null & isFactoryChk.isSelected()){
            aliProductExample.createCriteria().andIsFactoryEqualTo(1);
        }
        if(catalogProperty.getValue()>0){
            aliProductExample.createCriteria().andCateIdEqualTo(catalogProperty.get());
        }
        List<AliProduct> aliProducts = dataManager.selectAliProdutList(aliProductExample);

       data = FXCollections.observableArrayList();

        aliProducts.forEach(t->{
            data.add(new AliProductView(t));
        });
       // data = FXCollections.observableArrayList();
        tableView.setItems(data);
        return data;
    }

    public void createToolBar(BorderPane borderPane){
        ToolBar toolBar =new ToolBar();
        Button button= new Button("刷新分类");
            button.setOnAction(event -> {

//            AliCataLogTreeItem root = (AliCataLogTreeItem) treeTableView.getRoot();
//            root.getChildren().add(new AliCataLogTreeItem(aliCatalogTree));
             bindTreeTableView();
        });
        toolBar.getItems().add(button);

        Button btnGetSelectRow = new Button("刷新商品");
        btnGetSelectRow.setOnAction(event -> {

            initTableViewData();
        });
        Button btnAll = new Button("全部商品");
        btnAll.setOnAction(event -> {
            catalogProperty.setValue(-1);
            initTableViewData();
        });
        //toolBar.getItems().add(btnGetSelectRow);

        HBox hBox = new HBox();
//        vBox.setFillWidth(true);

        createSearchPane(hBox);
        hBox.getChildren().addAll(btnGetSelectRow,btnAll);

        hBox.setAlignment(Pos.CENTER);
        hBox.setSpacing(5);

        toolBar.getItems().addAll(hBox);

        borderPane.setTop(toolBar);
    }

    public void createSearchPane(Pane pane){

        proNameTxt = new TextField();
        proNameTxt.setPrefWidth(200);
        Label label = new Label("商品名称");

        Label label1 = new Label("实力商家");
        isShiliChk = new CheckBox();

        Label label2 = new Label("工厂直销");
        isFactoryChk = new CheckBox();



        pane.getChildren().addAll(label,proNameTxt,label1,isShiliChk,label2,isFactoryChk);
    }

    public void iniUI(){

    }

    private TableView<AliProductView> buildProductTableView(){
        TableView<AliProductView> aliProductTableView = new TableView<AliProductView>();

        TableColumn<AliProductView, String> proNameCol, proviCol, shopNameCol,picUrlName;

        TableColumn<AliProductView,Boolean> shiliCol, factoryCol,isSelectCol;
        // Columns

        //checkBox
        TableColumn<AliProductView, Boolean> invitedCol = new TableColumnHelper<AliProductView,Boolean>("选择",55,"isSelected",true, p->new CheckBoxTableCell<AliProductView,Boolean>());
        invitedCol.setOnEditCommit(
                (TableColumn.CellEditEvent<AliProductView, Boolean> t) -> {
                    ((AliProductView) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setIsFactory(t.getNewValue());
                });


        proNameCol = new TableColumnHelper<>("商品",200,"name",true,TextFieldTableCell.<AliProductView>forTableColumn());
        proNameCol.setOnEditCommit(t -> System.out.println("Edit commit event: " + t.getNewValue()));

        proviCol = new TableColumnHelper<>("供应商",200,"proviName",true,TextFieldTableCell.<AliProductView>forTableColumn());

        shopNameCol = new TableColumnHelper<>("店铺", 200, "shopName", false,
                new Callback<TableColumn<AliProductView,String>,TableCell<AliProductView,String>>() {
                    @Override
                    public TableCell<AliProductView, String> call(TableColumn<AliProductView, String> param) {


                        TableCell<AliProductView, String> cell = new TableCell<AliProductView,String>(){
                            @Override
                            protected void updateItem(String item, boolean empty) {
                                Hyperlink hyperlink = new Hyperlink(item);
                                hyperlink.setOnAction(event -> {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION,"hyper link click");
                                    alert.show();
                                });
                                setGraphic(hyperlink);
                            }
                        };
                       cell.setOnMouseClicked((MouseEvent t) -> {
                            if (t.getClickCount() == 2) {
                                Alert alert = new Alert(Alert.AlertType.INFORMATION,"double click");
                                alert.show();
                            }
                        });
                        return cell;
                    }
                });

        shiliCol = new TableColumnHelper<AliProductView,Boolean>("实力商家",100,"isShili",false, p->new CheckBoxTableCell<AliProductView,Boolean>());//new TableColumn<AliProductView, Boolean>();

        factoryCol = new TableColumnHelper<AliProductView,Boolean>("工厂直销",100,"isFactory",false, p->new CheckBoxTableCell<AliProductView,Boolean>());

        TableColumn<AliProductView,String>  priceModelCol = new TableColumnHelper<>("批发价1",200,"",false,null);

       TableColumn<AliProductView,String>  numCol1 = new TableColumnHelper<>("数量",100,"start1",false,null);

        TableColumn<AliProductView,String>  priceCol1 = new TableColumnHelper<>("单价",100,"price1",false,null);

        priceModelCol.getColumns().addAll(numCol1,priceCol1);


        TableColumn<AliProductView,String>  priceModelCol2 = new TableColumnHelper<>("批发价2",200,"",false,null);

        TableColumn<AliProductView,String>  numCol2 = new TableColumnHelper<>("数量",100,"start1",false,null);

        TableColumn<AliProductView,String>  priceCol2 = new TableColumnHelper<>("单价",100,"price1",false,null);

        priceModelCol2.getColumns().addAll(numCol2,priceCol2);



        TableColumn<AliProductView,String>  priceModelCol3 = new TableColumnHelper<>("批发价1",200,"",false,null);

        TableColumn<AliProductView,String>  numCol3 = new TableColumnHelper<>("数量",100,"start1",false,null);

        TableColumn<AliProductView,String>  priceCol3 = new TableColumnHelper<>("单价",100,"price1",false,null);

        priceModelCol3.getColumns().addAll(numCol3,priceCol3);


        TableView<AliProductView> tableView = new TableView<AliProductView>();
        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        //tableView.getSelectionModel().setCellSelectionEnabled(true);
        tableView.setTableMenuButtonVisible(true);
        tableView.setItems(data);
        tableView.getColumns().addAll(invitedCol,proNameCol,proviCol, shopNameCol,priceModelCol,priceModelCol2,priceModelCol3, shiliCol, factoryCol);
        //tableView.setPrefSize(width, 300);
        tableView.setEditable(true);
        tableView.getSortOrder().addAll(proNameCol,proviCol,shiliCol,factoryCol);
        //行双击
        tableView.setRowFactory(param -> {
            TableRow<AliProductView> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                    AliProductView rowData = row.getItem();
                    System.out.println(rowData.getName());
                }
            });
            return row ;
        });
        this.tableView = tableView;
        return tableView;
        //return  aliProductTableView;
    }

    private  TreeTableView buildAliCatalogTreeTableView() {
        // create a simple String treeview
       // root.setExpanded(true);
       
        final TreeTableView<AliCatalogTree> treeTableView = new TreeTableView<AliCatalogTree>();
        treeTableView.setShowRoot(false);
       // treeTableView.setRoot(root);
        treeTableView.setMaxWidth(200);

        // --- name column
        TreeTableColumn<AliCatalogTree, String> nameColumn = new TreeTableColumn<AliCatalogTree, String>("类名");
        nameColumn.setPrefWidth(200);
        nameColumn.setCellValueFactory(p -> {
            AliCatalogTree f = p.getValue().getValue();
            String text =  f.getName();
            return new ReadOnlyObjectWrapper<String>(text);
        });
        
        treeTableView.getColumns().setAll(nameColumn);

        treeTableView.setOnMousePressed(event -> {
            TreeItem<AliCatalogTree> selectedItem = treeTableView.getSelectionModel().getSelectedItem();
            if(selectedItem!=null){
                catalogProperty.set(selectedItem.getValue().getId());
                initTableViewData();
            }
            //logger.info("treetableview select:" + name);
        });
        this.treeTableView = treeTableView;
        bindTreeTableView();
        return treeTableView;
    }

    private void bindTreeTableView(){
        List<AliCatalogTree> showList =  dataManager.getParentCatalogList(); // new FileTreeItem(ROOT);
        AliCatalogTree aliCatalogTree = new AliCatalogTree();
        aliCatalogTree.setId(0L);
        aliCatalogTree.setIsParent(1);
        aliCatalogTree.setChildrens(showList);

        AliCataLogTreeItem root = new AliCataLogTreeItem(aliCatalogTree);
        treeTableView.setRoot(root);
        treeTableView.refresh();

    }
}
